package com.sx.web.player.servlet;

import com.sun.scenario.effect.impl.sw.java.JSWBlend_SRC_OUTPeer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Base64;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter writer = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    System.out.println(username);
    System.out.println(password);
    if(!"2019401264".equals(username)||!"123456".equals(password)) {
      writer.print("no");
    }else {
      request.getSession().setAttribute("username","佘欣");
      writer.print("ok");
    }
  }

  /**
   * 给用户名和密码加密的方法
   * @param rememberMe
   * @param username
   * @param password
   * @param request
   * @param response
   * @throws UnsupportedEncodingException
   */

  private void rememberMe(String rememberMe, String username, String password, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
    if("true".equals(rememberMe)) {
      Cookie cookie = new Cookie("username", Base64.getEncoder().encodeToString(username.getBytes()));
      cookie.setPath("/");
      cookie.setMaxAge(365*24*3600);
      response.addCookie(cookie);
      cookie = new Cookie("password", Base64.getEncoder().encodeToString(password.getBytes()));
      cookie.setPath("/");
      cookie.setMaxAge(365*24*3600);
      response.addCookie(cookie);
    } else {
      Cookie[] cookies = request.getCookies();
      if(cookies != null) {
        for (Cookie cookie : cookies) {
          if("username".equals(cookie.getName())||"password".equals(cookie.getName())) {
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
          }
        }
      }
    }
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
  }
}
